<template>
  <div class="app-container">
    <div class="search-container">
      <el-form :model="searchParam" :inline="true">
        <el-form-item label="成品物料">
          <el-input
            v-model="searchParam.materialCode"
            placeholder="请选择成品物料"
            clearable
            readonly
            style="width: 100%"
            @click="showWorkOrderSelect"
          >
            <template #append>
              <el-button type="success" plain @click="showWorkOrderSelect"
                >选择</el-button
              >
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="生产版本编号">
          <el-input
            v-model="searchParam.versionNo"
            placeholder="请输入生产版本编号"
            clearable
            @keyup.enter="search"
          />
        </el-form-item>
        <el-form-item label="启用状态">
          <el-select
            v-model="searchParam.enabled"
            placeholder="请选择启用状态"
            clearable
            @change="changeOpeType"
          >
            <el-option
              v-for="item in useDictionary('Enabled')"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search"
            ><i-ep-search />搜索</el-button
          >
          <el-button @click="resetHandle"><i-ep-refresh />重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button type="success" plain @click="addItem()"
          ><i-ep-plus />新增</el-button
        >
        <el-button
          type="primary"
          plain
          @click="copyItem()"
          :disabled="ids.length === 0"
          ><i-ep:document-copy />复制</el-button
        >
      </template>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="tableData"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column
          label="工厂"
          prop="plantCode"
          min-width="100"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="生产版本编号"
          prop="versionNo"
          min-width="130"
          show-overflow-tooltip
        />
        <el-table-column
          label="版本描述"
          prop="remarks"
          min-width="100"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="成品物料号"
          prop="materialCode"
          min-width="120"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="成品物料名称"
          prop="materialName"
          min-width="180"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="成品BOM编号"
          prop="bomCode"
          min-width="130"
          show-overflow-tooltip
        />
        <el-table-column
          label="启用状态"
          prop="enabled"
          min-width="100"
          show-overflow-tooltip
          align="center"
        >
          <template #default="scope">
            <el-tag type="success" v-if="scope.row.enabled === 1">启用</el-tag>
            <el-tag type="info" v-else>停用</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="创建时间"
          prop="createTime"
          min-width="160"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="创建人"
          prop="createdUserName"
          min-width="100"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="更新时间"
          prop="lastUpdateTime"
          min-width="160"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="更新人"
          prop="lastUpdatedUserName"
          min-width="100"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column fixed="right" label="操作" width="240" align="center">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              link
              @click="editItem(scope.row.id)"
              ><i-ep-edit />编辑</el-button
            >
            <el-button
              type="primary"
              size="small"
              link
              :disabled="scope.row.bind"
              @click="deleteItem(scope.row.id)"
              ><i-ep-delete />删除</el-button
            >
            <el-button
              type="primary"
              size="small"
              link
              :disabled="!scope.row.enabled"
              @click="stopItem(scope.row.id)"
              ><i-ep-delete />停用</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        :background="true"
        :current-page="pageable.pageNum"
        :page-size="pageable.pageSize"
        :page-sizes="[10, 25, 50, 100]"
        :total="pageable.total"
        layout="total, sizes, prev, pager, next, jumper"
        class="mt-[20px]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <material-select
      :visible="selectDialogSELECT.visible"
      @change-visible="changeVisibleSELECT"
      :brekList="brekList"
    />
    <processTemplate />
    <productionVersionEdit />
  </div>
</template>

<script setup lang="ts">
import { useTable, useDownload, useDictionary } from "@/utils/useTable";
import request from "@/utils/request";
import { checkCommon } from "@/views/qms/checkHook/checkCommon";
import useEvent from "@/utils/useEvent";
import { productionVersionHook } from "@/views/mes/produceVersion/hook/productionVersionHook";
import { ElDialog } from "element-plus";

defineOptions({
  name: "PRODUCTIONVERSION",
  inheritAttrs: false,
});
const { eventBusEmit, eventBusOn } = useEvent();

const { event, api } = productionVersionHook();

const dataTableRef = ref(null);
// 请求参数
const requestApi = api.page;

// 是否需要分页
const pagination = true;

const initParam = {};

// 初始化搜索参数数据
const searchParamInit = {
  materialId: "",
  versionNo: "",
  enabled: "",
  materialCode: "",
};

const deleteParam = {
  api: api.delete,
  data: {},
};

// 数据请求错误后处理
function requestError() {}

const materialList = ref([]);

const dataCallBack = ref(undefined); // 无需二次数据处理&不传赞数也行

// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  ids,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  handleTableDelete,
  loading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack.value,
  requestError,
  deleteParam
);
const { getEffectTypeCode, changeOpeType, resetHandle } = checkCommon(
  searchParam,
  reset
);
onMounted(() => {
  getTableList();
  eventBusOn(event.refreshEvent, () => {
    getTableList();
  });
});

const handleSelectionChange = (list: any) => {
  ids.value = [];
  if (list.length > 1) {
    dataTableRef.value.clearSelection();
    dataTableRef.value.toggleRowSelection(list[list.length - 1]);
  }
  ids.value = [list[list.length - 1]?.id];
};

// 查询详情
async function getInfo(id: string) {
  const { data } = await request({
    url: `${api.get}/${id}`,
    method: "get",
  });
  return data;
}
/** 打开标准检验项目表单弹窗 详情 */
function openDialogdetail(roleObj?: any) {
  addDialog.title = "标准检验项目详情";
  getInfo(roleObj.id);
  addDialog.readvisible = true;
}

function changeVisible(value: boolean) {
  addDialog.visible = value;
  if (!value) {
    addDialog.data = {};
  }
}

async function deleteItem(id: any) {
  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    const { data } = await request({
      url: `${api.deleteItem}/${id}`,
      method: "post",
    });
    search();
  });
}
const addItem = () => {
  eventBusEmit(event.addEvent);
};
const copyItem = () => {
  ElMessageBox.confirm("确认复制已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    const { data } = await request({
      url: `${api.copy}/${ids.value[0]}`,
      method: "get",
      data: {},
    });
    eventBusEmit(event.copyEvent, data);
  });
};
const editItem = async (id) => {
  const info = await getInfo(id);
  eventBusEmit(event.editEvent, info);
};
const stopItem = (id) => {
  ElMessageBox.confirm("确认停用已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    const { data } = await request({
      url: api.stopUsing,
      method: "post",
      data: { ids: [id] },
    });
    search();
  });
};

//选择物料弹窗
const selectDialogSELECT = ref({
  visible: false,
});
const changeVisibleSELECT = (val: boolean, data: any) => {
  selectDialogSELECT.value.visible = val;
  if (data) {
    searchParam.value.materialId = data.id;
    searchParam.value.materialCode = data.materialCode;
  }
};
// 回显的数据
const brekList = ref([]);
const showWorkOrderSelect = () => {
  selectDialogSELECT.value.visible = true;
};
</script>
<style scoped>
::v-deep .el-table__header-wrapper th.el-table-column--selection .cell .el-checkbox {
  display: none;
}
::v-deep .equip-form-item > .el-form-item__content {
  display: flex;
  justify-content: center;
}
</style>
